<?php

namespace app\common\controller;

use app\admin\model\TeacherArea;
use app\admin\model\TeacherDetail;
use OSS\Core\OssException;
use OSS\OssClient;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

class Wordcreate
{

    private $tempFiles = [];

    /**
     * 生成教师身份信息Word文档
     */
    public function generate_word_document($user_id,$detailId)
    {
//        $user = $this->auth->getUser();
//        if (!isset($user['id']) || !$user['id']) {
//            $this->error('当前登录用户不存在');
//        }
        if(!isset($user_id)||!$user_id){
            return ['code'=>0,'msg'=>'缺少用户id'];
        }
        if(!isset($detailId)||!$detailId){
            return ['code'=>0,'msg'=>'缺少用户id'];
        }
        // 获取教师身份信息
        $identityInfo = \app\admin\model\IdentityInfo::where(['user_id' => $user_id, 'identity_type' => '教师'])->with(['user','club_dtl_s'])->find();
        if (!$identityInfo) {
            return ['code'=>0,'msg'=>'教师身份信息不存在'];
        }
        $detail = TeacherDetail::where(['id'=>$detailId])->with(['club_dtl_s'])->find();
        if (!$detail) {
            return ['code'=>0,'msg'=>'教师社团信息不存在'];
        }
        // 处理数据
        $data = $this->processIdentityData($identityInfo,$detail);

        // 生成Word文档
        $result = $this->createWordDocument($data);

        if ($result) {
            if (is_array($result) && isset($result['oss_url'])) {
                // 上传到OSS成功
                return ['code'=>1,'msg'=>'文档生成并上传成功','filename'=>$result['filename'],'oss_url'=>$result['oss_url']];
//                $this->success('文档生成并上传成功', [
//                    'filename' => $result['filename'],
//                    'oss_url' => $result['oss_url'],
//                    'download_url' => $result['oss_url']
//                ]);
            } else {
                // 本地保存成功
                return ['code'=>1,'msg'=>'文档生成成功','filename'=>$result,'oss_url'=>'/api/identity_info/download_word?filename=' . urlencode($result)];
//                $this->success('文档生成成功', [
//                    'filename' => $result,
//                    'download_url' => '/api/identity_info/download_word?filename=' . urlencode($result)
//                ]);
            }
        } else {
            return ['code'=>0,'msg'=>'文档生成失败'];
//            $this->error('文档生成失败');
        }
    }
    public function generate_word_document_old($user_id)
    {
//        $user = $this->auth->getUser();
//        if (!isset($user['id']) || !$user['id']) {
//            $this->error('当前登录用户不存在');
//        }
        if(!isset($user_id)||!$user_id){
            return ['code'=>0,'msg'=>'缺少用户id'];
        }
        // 获取教师身份信息
        $identityInfo = \app\admin\model\IdentityInfo::where(['user_id' => $user_id, 'identity_type' => '教师'])->with(['user','club_dtl_s'])->find();
        if (!$identityInfo) {
            return ['code'=>0,'msg'=>'教师身份信息不存在'];
        }
        // 处理数据
        $data = $this->processIdentityData($identityInfo);

        // 生成Word文档
        $result = $this->createWordDocument($data);

        if ($result) {
            if (is_array($result) && isset($result['oss_url'])) {
                // 上传到OSS成功
                return ['code'=>1,'msg'=>'文档生成并上传成功','filename'=>$result['filename'],'oss_url'=>$result['oss_url']];
            } else {
                // 本地保存成功
                return ['code'=>1,'msg'=>'文档生成成功','filename'=>$result,'oss_url'=>'/api/identity_info/download_word?filename=' . urlencode($result)];
            }
        } else {
            return ['code'=>0,'msg'=>'文档生成失败'];
//            $this->error('文档生成失败');
        }
    }

    /**
     * 处理身份信息数据
     */
    private function processIdentityData($identityInfo,$detail)
    {
        $data = $identityInfo->toArray();
        $detail_arr = $detail->toArray();

        // 处理图片数组d
        $data['img_arr'] = $detail_arr['imgs'] ? explode(',', $detail_arr['imgs']) : [];
        $data['teacher_certification_arr'] = $detail_arr['teacher_certification'] ? explode(',', $detail_arr['teacher_certification']) : [];
        $data['diploma_arr'] = $detail_arr['diploma'] ? explode(',', $detail_arr['diploma']) : [];
        $data['occupational_qualifications_arr'] = $detail_arr['occupational_qualifications'] ? explode(',', $detail_arr['occupational_qualifications']) : [];
        $data['professional_skill_arr'] = $detail_arr['professional_skill'] ? explode(',', $detail_arr['professional_skill']) : [];
        $data['health_certificate_arr'] = $detail_arr['health_certificate'] ? explode(',', $detail_arr['health_certificate']) : [];
        $data['identity_card_img_arr'] = $detail_arr['identity_card_img'] ? explode(',', $detail_arr['identity_card_img']) : [];
        $data['no_crime_arr'] = $detail_arr['no_crime'] ? explode(',', $detail_arr['no_crime']) : [];

        // 处理区域名称
        $area = $identityInfo['area'] ? explode(',', $identityInfo['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k => $v) {
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v] . ',' : '';
        }
        $data['area_name'] = trim($area_name, ',');

        // 处理用户性别
        $user_find = \app\admin\model\User::where(['id' => $identityInfo['user_id']])->find();
        if ($user_find['gender'] == 1) {
            $data['sex'] = '男';
        } else {
            $data['sex'] = '女';
        }

        // 处理工作年限
        $data['work_time_display'] = $detail_arr['work_time'] ? $detail_arr['work_time'] . '年' : '';
        $data['club_dtl_name'] = isset($detail_arr['club_dtl_s']) ? $detail_arr['club_dtl_s']['name'] : '';
        $data['avatar'] = isset($identityInfo['user']) ? $identityInfo['user']['avatar'] : '';


        $data['hourly_rate'] = $detail_arr['hourly_rate'] ? $detail_arr['hourly_rate']: '';
        $data['appointment_time_week'] = $detail_arr['appointment_time_week'] ? $detail_arr['appointment_time_week']: '';
        $data['appointment_time'] = $detail_arr['appointment_time'] ? $detail_arr['appointment_time']: '';
        $data['teacher_certification'] = $detail_arr['teacher_certification'] ? $detail_arr['teacher_certification']: '';
        $data['diploma'] = $detail_arr['diploma'] ? $detail_arr['diploma']: '';
        $data['occupational_qualifications'] = $detail_arr['occupational_qualifications'] ? $detail_arr['occupational_qualifications']: '';
        $data['course_outline'] = $detail_arr['course_outline'] ? $detail_arr['course_outline']: '';
        $data['teaching_objectives'] = $detail_arr['teaching_objectives'] ? $detail_arr['teaching_objectives']: '';
        $data['knowledge_requirements'] = $detail_arr['knowledge_requirements'] ? $detail_arr['knowledge_requirements']: '';
        $data['imgs'] = $detail_arr['imgs'] ? $detail_arr['imgs']: '';
        $data['addtime'] = $detail_arr['addtime'] ? $detail_arr['addtime']: '';
        $data['sort'] = $detail_arr['sort'] ? $detail_arr['sort']: '';
        $data['tag'] = $detail_arr['tag'] ? $detail_arr['tag']: '';
        $data['score'] = $detail_arr['score'] ? $detail_arr['score']: '';
        $data['user_score'] = $detail_arr['user_score'] ? $detail_arr['user_score']: '';
        $data['people'] = $detail_arr['people'] ? $detail_arr['people']: '';
        $data['personal_resume'] = $detail_arr['personal_resume'] ? $detail_arr['personal_resume']: '';
        $data['professional_skill'] = $detail_arr['professional_skill'] ? $detail_arr['professional_skill']: '';
        $data['health_certificate'] = $detail_arr['health_certificate'] ? $detail_arr['health_certificate']: '';
        $data['identity_card_img'] = $detail_arr['identity_card_img'] ? $detail_arr['identity_card_img']: '';
        $data['no_crime'] = $detail_arr['no_crime'] ? $detail_arr['no_crime']: '';
        $data['is_all'] = $detail_arr['is_all'] ? $detail_arr['is_all']: '';
        $data['educational_back'] = $detail_arr['educational_back'] ? $detail_arr['educational_back']: '';
        $data['work_experience'] = $detail_arr['work_experience'] ? $detail_arr['work_experience']: '';
        $data['certificate_reward'] = $detail_arr['certificate_reward'] ? $detail_arr['certificate_reward']: '';
        $data['self_assessment'] = $detail_arr['self_assessment'] ? $detail_arr['self_assessment']: '';
        $data['tag_me'] = $detail_arr['tag_me'] ? $detail_arr['tag_me']: '';
        $data['jxjh'] = $detail_arr['jxjh'] ? $detail_arr['jxjh']: '';
        $data['work_time'] = $detail_arr['work_time'] ? $detail_arr['work_time']: '';
        $data['education_background'] = $detail_arr['education_background'] ? $detail_arr['education_background']: '';
        $data['is_premium'] = $detail_arr['is_premium'] ? $detail_arr['is_premium']: '';
        $data['word_file'] = $detail_arr['word_file'] ? $detail_arr['word_file']: '';
        return $data;
    }
    private function processIdentityDataOld($identityInfo)
    {
        $data = $identityInfo->toArray();

        // 处理图片数组
        $data['img_arr'] = $identityInfo['imgs'] ? explode(',', $identityInfo['imgs']) : [];
        $data['teacher_certification_arr'] = $identityInfo['teacher_certification'] ? explode(',', $identityInfo['teacher_certification']) : [];
        $data['diploma_arr'] = $identityInfo['diploma'] ? explode(',', $identityInfo['diploma']) : [];
        $data['occupational_qualifications_arr'] = $identityInfo['occupational_qualifications'] ? explode(',', $identityInfo['occupational_qualifications']) : [];
        $data['professional_skill_arr'] = $identityInfo['professional_skill'] ? explode(',', $identityInfo['professional_skill']) : [];
        $data['health_certificate_arr'] = $identityInfo['health_certificate'] ? explode(',', $identityInfo['health_certificate']) : [];
        $data['identity_card_img_arr'] = $identityInfo['identity_card_img'] ? explode(',', $identityInfo['identity_card_img']) : [];
        $data['no_crime_arr'] = $identityInfo['no_crime'] ? explode(',', $identityInfo['no_crime']) : [];

        // 处理区域名称
        $area = $identityInfo['area'] ? explode(',', $identityInfo['area']) : [];
        $area_arr = TeacherArea::get_arr();
        $area_name = '';
        foreach ($area as $k => $v) {
            $area_name .= isset($area_arr[$v]) ? $area_arr[$v] . ',' : '';
        }
        $data['area_name'] = trim($area_name, ',');

        // 处理用户性别
        $user_find = \app\admin\model\User::where(['id' => $identityInfo['user_id']])->find();
        if ($user_find['gender'] == 1) {
            $data['sex'] = '男';
        } else {
            $data['sex'] = '女';
        }

        // 处理工作年限
        $data['work_time_display'] = $identityInfo['work_time'] ? $identityInfo['work_time'] . '年' : '';
        $data['club_dtl_name'] = isset($identityInfo['club_dtl_s']) ? $identityInfo['club_dtl_s']['name'] : '';
        $data['avatar'] = isset($identityInfo['user']) ? $identityInfo['user']['avatar'] : '';
        return $data;
    }

    /**
     * 创建Word文档
     */
    private function createWordDocument($data)
    {
        try {
            // 创建PHPWord对象
            $phpWord = new PhpWord();

            // 设置文档属性
            $phpWord->getDocInfo()->setCreator('下午活动中心')
                ->setLastModifiedBy('下午活动中心')
                ->setTitle('教师身份信息表')
                ->setSubject('教师身份信息')
                ->setDescription('教师身份信息详细资料')
                ->setKeywords('教师,身份信息,下午活动中心')
                ->setCategory('身份信息');

            // 设置默认字体
            $phpWord->setDefaultFontName('微软雅黑');
            $phpWord->setDefaultFontSize(12);

            // 添加标题
            $phpWord->addTitleStyle(1, ['name' => '微软雅黑', 'size' => 18, 'bold' => true], ['alignment' => 'center']);
            $phpWord->addTitleStyle(2, ['name' => '微软雅黑', 'size' => 14, 'bold' => true]);
            $phpWord->addTitleStyle(3, ['name' => '微软雅黑', 'size' => 12, 'bold' => true]);

            // 开始添加内容
            $section = $phpWord->addSection([
                'marginTop' => 1134,
                'marginBottom' => 1134,
                'marginLeft' => 1134,
                'marginRight' => 1134,
            ]);

            // 主标题
            $section->addTitle('教师身份信息表', 1);
            $section->addTextBreak(1);

            // 基本信息
            $section->addTitle('一、基本信息', 2);
            $this->addBasicInfo($section, $data);
            $section->addTextBreak(1);

            // 教育背景
            $section->addTitle('二、个人简历', 2);
            $this->addEducationInfo($section, $data);
            $section->addTextBreak(1);

            // 工作经历
            $section->addTitle('三、教师资质', 2);
            $this->addWorkExperience($section, $data);
            $section->addTextBreak(1);

            // 专业技能
            $section->addTitle('四、课程信息', 2);
            $this->addProfessionalSkills($section, $data);
            $section->addTextBreak(1);
//
//            // 身份证明
//            $section->addTitle('五、身份证明', 2);
//            $this->addIdentityDocuments($section, $data);
//            $section->addTextBreak(1);
//
//            // 教学信息
//            $section->addTitle('六、教学信息', 2);
//            $this->addTeachingInfo($section, $data);
//            $section->addTextBreak(1);
//
//            // 其他信息
//            $section->addTitle('七、其他信息', 2);
//            $this->addOtherInfo($section, $data);

            // 生成文件名
            $filename = $data['name'] . '_教师身份信息_' . date('YmdHis') . '.docx';
            $filepath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'word' . DS;

            // 确保目录存在
            if (!is_dir($filepath)) {
                mkdir($filepath, 0755, true);
            }

            $fullPath = $filepath . $filename;

            // 保存文档
            $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
            $objWriter->save($fullPath);

            // 上传到OSS
            $ossUrl = $this->uploadToOSS($fullPath, $filename);

            // 清理临时文件
            $this->cleanupTempFiles();

            // 删除本地文件（如果上传成功）
            if ($ossUrl) {
                @unlink($fullPath);
                return ['filename' => $filename, 'oss_url' => $ossUrl];
            }

            return $filename;

        } catch (\Exception $e) {
            \think\Log::error('生成Word文档失败: ' . $e->getMessage());
            // 即使出错也要清理临时文件
            $this->cleanupTempFiles();
            return false;
        }
    }

    /**
     * 清理临时文件
     */
    private function cleanupTempFiles()
    {
        foreach ($this->tempFiles as $tempFile) {
            if (file_exists($tempFile)) {
                @unlink($tempFile);
                \think\Log::info('删除临时文件: ' . $tempFile);
            }
        }
        // 清空临时文件列表
        $this->tempFiles = [];
    }

    /**
     * 上传文件到OSS
     */
    private function uploadToOSS($filePath, $filename)
    {
        try {
            // 获取OSS配置
            $config = get_addon_config('alioss');
            if (!$config) {
                \think\Log::error('OSS配置不存在');
                return false;
            }

            // 创建OSS客户端
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

            // 生成OSS存储路径
            $ossKey = '/uploads/word/' . date('Ymd') . '/' . $filename;

            \think\Log::info('开始上传文件到OSS: ' . $filePath . ' -> ' . $ossKey);

            // 上传文件到OSS
            $result = $ossClient->uploadFile($config['bucket'], ltrim($ossKey, '/'), $filePath);

            if ($result && isset($result['info']['url'])) {
                $ossUrl = $result['info']['url'];
                \think\Log::info('文件上传到OSS成功: ' . $ossUrl);
                return $ossUrl;
            } else {
                \think\Log::error('OSS上传失败，未返回URL');
                return false;
            }

        } catch (OssException $e) {
            \think\Log::error('OSS上传异常: ' . $e->getMessage());
            return false;
        } catch (\Exception $e) {
            \think\Log::error('上传文件到OSS失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 添加基本信息
     */
    private function addBasicInfo($section, $data)
    {
        $table = $section->addTable(['borderSize' => 6, 'borderColor' => '000000']);

        $this->addTableRow($table, '姓名', $data['name'] ?? '');
        $this->addTableRow($table, '电话', $data['phone'] ?? '');
        $this->addTableRow($table, '年龄', $data['age'] ?? '');
        $this->addTableRow($table, '性别', $data['sex'] ?? '');
        $this->addTableRow($table, '教学经验', $data['work_time_display'] ?? '');
        $this->addTableRow($table, '最高学历', $data['education_background'] ?? '');
        $this->addTableRow($table, '所属社团', $data['club_dtl_name'] ?? '');
        $this->addTableRow($table, '服务区域', $data['area_name'] ?? '');
        $this->addTableRow($table, '课时费用', ($data['hourly_rate'] ?? '') . '元/节');
        $this->addTableRow($table, '可约时间', ($data['appointment_time_week'] ?? '') . ' ' . ($data['appointment_time'] ?? ''));

        // 添加头像
        if (!empty($data['avatar']) && $this->isImagePath($data['avatar'])) {
            $section->addText('头像:', ['bold' => true]);
            $this->addImageToSection($section, $data['avatar'], '头像');
        }
        // 封面图片
        if (!empty($data['img_arr'])) {
            $section->addText('封面图片:', ['bold' => true]);
            foreach ($data['img_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '封面图片');
                }
            }
        }
    }

    /**
     * 添加个人简历
     */
    private function addEducationInfo($section, $data)
    {
        if (!empty($data['educational_back'])) {
            $section->addText('教育背景:', ['bold' => true]);
            $section->addText($data['educational_back']);
            $section->addTextBreak(1);
        }
        if (!empty($data['work_experience'])) {
            $section->addText('工作经历:', ['bold' => true]);
            $section->addText($data['work_experience']);
            $section->addTextBreak(1);
        }
        if (!empty($data['certificate_reward'])) {
            $section->addText('证书奖励:', ['bold' => true]);
            $section->addText($data['certificate_reward']);
            $section->addTextBreak(1);
        }

        if (!empty($data['self_assessment'])) {
            $section->addText('自我评价:', ['bold' => true]);
            $section->addText($data['self_assessment']);
            $section->addTextBreak(1);
        }
    }

    /**
     * 添加教师资质
     */
    private function addWorkExperience($section, $data)
    {
        // 教师资格证
        if (!empty($data['teacher_certification_arr'])) {
            $section->addText('教师资格证:', ['bold' => true]);
            foreach ($data['teacher_certification_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '教师资格证');
                }
            }
        }
        // 职业资格证书
        if (!empty($data['occupational_qualifications_arr'])) {
            $section->addText('获奖证书:', ['bold' => true]);
            foreach ($data['occupational_qualifications_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '获奖证书');
                }
            }
        }
        // 毕业证书
        if (!empty($data['diploma_arr'])) {
            $section->addText('毕业证书:', ['bold' => true]);
            foreach ($data['diploma_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '毕业证书');
                }
            }
        }

    }

    /**
     * 添加课程信息
     */
    private function addProfessionalSkills($section, $data)
    {

        if (!empty($data['course_outline'])) {
            $section->addText('课程简介:', ['bold' => true]);
            $section->addText($data['course_outline']);
            $section->addTextBreak(1);
        }

        if (!empty($data['teaching_objectives'])) {
            $section->addText('教学目标:', ['bold' => true]);
            $section->addText($data['teaching_objectives']);
            $section->addTextBreak(1);
        }
//
//        if (!empty($data['knowledge_requirements'])) {
//            $section->addText('预备知识要求:', ['bold' => true]);
//            $section->addText($data['knowledge_requirements']);
//            $section->addTextBreak(1);
//        }

        if (!empty($data['jxjh'])) {
            $section->addText('教学计划:', ['bold' => true]);
            $section->addText($data['jxjh']);
            $section->addTextBreak(1);
        }

//        // 专业技能证书
//        if (!empty($data['professional_skill_arr'])) {
//            $section->addText('专业技能证书:', ['bold' => true]);
//            foreach ($data['professional_skill_arr'] as $image) {
//                if ($this->isImagePath($image)) {
//                    $this->addImageToSection($section, $image, '专业技能证书');
//                }
//            }
//        }
    }

    /**
     * 添加身份证明
     */
    private function addIdentityDocuments($section, $data)
    {
        // 身份证
        if (!empty($data['identity_card_img_arr'])) {
            $section->addText('身份证复印件:', ['bold' => true]);
            foreach ($data['identity_card_img_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '身份证');
                }
            }
        }

        // 健康证
        if (!empty($data['health_certificate_arr'])) {
            $section->addText('健康证:', ['bold' => true]);
            foreach ($data['health_certificate_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '健康证');
                }
            }
        }

        // 无犯罪证明
        if (!empty($data['no_crime_arr'])) {
            $section->addText('无犯罪证明:', ['bold' => true]);
            foreach ($data['no_crime_arr'] as $image) {
                if ($this->isImagePath($image)) {
                    $this->addImageToSection($section, $image, '无犯罪证明');
                }
            }
        }
    }

    /**
     * 添加教学信息
     */
    private function addTeachingInfo($section, $data)
    {
    }

    /**
     * 添加其他信息
     */
    private function addOtherInfo($section, $data)
    {


    }

    /**
     * 添加表格行
     */
    private function addTableRow($table, $label, $value)
    {
        $table->addRow();
        $table->addCell(2000)->addText($label, ['bold' => true]);
        $table->addCell(4000)->addText($value);
    }

    /**
     * 添加图片到文档
     */
    private function addImageToSection($section, $imagePath, $altText = '')
    {
        try {
            $localPath = $this->downloadImageToLocal($imagePath);
            if ($localPath && file_exists($localPath)) {
                $section->addImage($localPath, [
                    'height' => 200,
                    'alignment' => 'left'
                ]);
                $section->addTextBreak(1);

                // 将临时文件路径添加到待删除列表，稍后统一删除
                $this->tempFiles[] = $localPath;
            }
        } catch (\Exception $e) {
            \think\Log::error('添加图片失败: ' . $e->getMessage());
        }
    }

    /**
     * 下载图片到本地临时目录
     */
    private function downloadImageToLocal($imagePath)
    {
        try {
            // 获取完整的图片URL
            $imageUrl = $this->getImageFullPath($imagePath);
            \think\Log::info('图片URL: ' . $imageUrl);

            // 如果是本地文件，直接返回
            if (strpos($imageUrl, 'http') !== 0) {
                $result = file_exists($imageUrl) ? $imageUrl : null;
                \think\Log::info('本地文件检查: ' . ($result ? '存在' : '不存在'));
                return $result;
            }

            // 创建临时目录
            $tempDir = ROOT_PATH . 'runtime' . DS . 'temp' . DS . 'word_images' . DS;
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0755, true);
            }

            // 生成临时文件名
            $extension = pathinfo($imagePath, PATHINFO_EXTENSION);
            $tempFileName = uniqid() . '_' . time() . '.' . $extension;
            $tempFilePath = $tempDir . $tempFileName;

            \think\Log::info('临时文件路径: ' . $tempFilePath);

            // 下载图片
            $imageData = $this->downloadImageFromUrl($imageUrl);
            if ($imageData === false || empty($imageData)) {
                \think\Log::error('图片下载失败或数据为空');
                return null;
            }

            \think\Log::info('图片数据大小: ' . strlen($imageData) . ' bytes');

            // 保存到临时文件
            $result = file_put_contents($tempFilePath, $imageData);
            if ($result === false) {
                \think\Log::error('保存临时文件失败');
                return null;
            }

            \think\Log::info('图片保存成功: ' . $tempFilePath);
            return $tempFilePath;

        } catch (\Exception $e) {
            \think\Log::error('下载图片失败: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * 从URL下载图片
     */
    private function downloadImageFromUrl($url)
    {
        try {
            \think\Log::info('开始下载图片: ' . $url);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Accept: image/webp,image/apng,image/*,*/*;q=0.8',
                'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
                'Cache-Control: no-cache'
            ]);

            $data = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);

            \think\Log::info('HTTP状态码: ' . $httpCode);
            if ($error) {
                \think\Log::error('CURL错误: ' . $error);
            }

            if ($httpCode === 200 && $data !== false && !empty($data)) {
                \think\Log::info('图片下载成功，数据大小: ' . strlen($data) . ' bytes');
                return $data;
            }

            \think\Log::error('图片下载失败 - HTTP状态码: ' . $httpCode . ', 数据大小: ' . strlen($data));
            return false;

        } catch (\Exception $e) {
            \think\Log::error('下载图片异常: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取图片完整路径
     */
    private function getImageFullPath($imagePath)
    {
        // 如果已经是完整的URL，直接返回
        if (strpos($imagePath, 'http') === 0) {
            return $imagePath;
        }

        // 如果是相对路径，拼接OSS域名
        if (strpos($imagePath, '/uploads/') === 0) {
            return 'https://ev-2022.oss-cn-shenzhen.aliyuncs.com' . $imagePath;
        }

        return $imagePath;
    }

    /**
     * 判断是否为图片路径
     */
    private function isImagePath($path)
    {
        if (empty($path)) {
            return false;
        }

        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));

        return in_array($extension, $imageExtensions);
    }

}